<template>
  <div class="app-container">
    <el-card class="queryForm">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-form-item label="活动名称" prop="campaignName">
          <el-input
            v-model="queryParams.campaignName"
            placeholder="请输入活动名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择活动状态"
            clearable
            style="width: 200px"
          >
            <el-option label="草稿" value="draft" />
            <el-option label="激活" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="common-card">
      <div class="btn-form">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >批量删除</el-button>
      </div>

      <el-table v-loading="loading" :data="marketingList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="活动ID" align="center" prop="id" />
        <el-table-column label="活动名称" align="center" prop="campaignName" />
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'draft'" type="info">草稿</el-tag>
            <el-tag v-else-if="scope.row.status === 'active'" type="success">激活</el-tag>
            <el-tag v-else-if="scope.row.status === 'completed'" type="primary">已完成</el-tag>
            <el-tag v-else-if="scope.row.status === 'cancelled'" type="danger">已取消</el-tag>
            <el-tag v-else>{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="140">
          <template #default="scope">
            <el-button icon="View" link @click="handleShow(scope.row)"></el-button>
            <el-button icon="Edit" link @click="handleUpdate(scope.row)"></el-button>
            <el-button icon="Delete" link @click="handleDelete(scope.row)" v-if="scope.row.status !== 'active'"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 编辑抽屉 -->
    <edit-drawer 
      :title="title" 
      :open="open" 
      ref="editDrawerRef"
      @submit="submitForm"
      @update:open="open = $event"
    ></edit-drawer>
    
    <!-- 详情页面 -->
    <detail-form 
      :title="detailTitle" 
      :open="detailOpen" 
      ref="detailRef"
      @update:open="detailOpen = $event"
    ></detail-form>
  </div>
</template>

<script setup name="Marketing" lang="ts">
import { ref, getCurrentInstance, reactive, toRefs, nextTick } from "vue";
import { ElForm } from "element-plus";
import modal from "@/plugins/modal";
import { parseTime } from "@/utils/Jinbooks";
import request from '@/utils/request';
import EditDrawer from './edit-drawer.vue';
import DetailForm from './detail.vue';

const { proxy } = getCurrentInstance()!;

// 字典数据
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

// 定义变量
const marketingList = ref([]);
const open = ref(false);
const loading = ref(true);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const ids = ref([]);
const detailOpen = ref(false);
const detailTitle = ref('');
const detailId = ref('');
const editDrawerRef = ref();
const detailRef = ref();

// 查询参数
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    activityName: undefined,
    status: undefined
  }
});

const { queryParams } = toRefs(data);
const queryRef = ref<InstanceType<typeof ElForm> | null>(null);

// 获取列表
function getList() {
  loading.value = true;
  request({
    url: '/marketing/campaign/fetch',
    method: 'get',
    params: {
      current: queryParams.value.pageNum,
      size: queryParams.value.pageSize,
      campaignName: queryParams.value.campaignName,
      status: queryParams.value.status
    }
  }).then(response => {
    marketingList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

// 查询
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置
function resetQuery() {
  queryRef.value?.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 营销活动状态修改
function handleStatusChange(row) {
  let text = row.status === 1 ? "启用" : "停用";
  modal.confirm("确认要\"" + text + "\"\"" + row.activityName + "\"活动吗？").then(function() {
    // 模拟修改状态
    modal.msgSuccess("操作成功");
    return Promise.resolve();
  }).catch(function() {
    row.status = row.status === 1 ? 0 : 1;
  });
}

// 新增
function handleAdd() {
  const form = {
    selectedMerchants: [],
    selectedTags: [],
    marketingMethods: [],
    smsTemplate: '',
    smsContent: '',
    emailTemplate: '',
    emailSubject: '',
    emailContent: '',
    wechatTemplate: '',
    wechatContent: '',
    triggerType: 'immediate',
    scheduledTime: '',
    taskType: 'once',
    recurringPattern: '',
    endTime: ''
  };
  editDrawerRef.value.setForm(form);
  open.value = true;
  title.value = "新增营销活动";
}

// 修改
function handleUpdate(row) {
  request({
    url: `/marketing/campaign/${row.id}`,
    method: 'get'
  }).then(response => {
    const campaignData = response.data;
    editDrawerRef.value.setForm(campaignData);
    open.value = true;
    title.value = "修改营销活动";
  }).catch(error => {
    console.error('获取营销活动详情失败:', error);
    modal.msgError('获取营销活动详情失败');
  });
}

// 查看详情
function handleShow(row) {
  request({
    url: `/marketing/campaign/${row.id}`,
    method: 'get'
  }).then(response => {
    const form = response.data;
    detailRef.value.setForm(form);
    detailOpen.value = true;
    detailTitle.value = "营销活动详情";
  });
}

// 删除
function handleDelete(row) {
  const campaignIds = row.id || ids.value;
  modal.confirm("是否确认删除营销活动编号为\"" + campaignIds + "\"的数据项？").then(function() {
    return request({
      url: `/marketing/campaign/batch`,
      method: 'delete',
      data: Array.isArray(campaignIds) ? campaignIds : [campaignIds]
    }).then(() => {
      modal.msgSuccess("删除成功");
      getList();
    });
  }).catch(() => {});
}

// 提交表单
function submitForm(form) {
  // 根据状态确定请求URL和方法
  const isUpdate = form.id && form.id !== null; // 判断是新增还是更新
  let url, method, action;
  
  if (isUpdate) {
    // 更新操作
    if (form.status === 'draft') {
      url = '/marketing/campaign/update';
      method = 'put';
      action = '保存草稿';
    } else {
      // 更新并执行，使用特殊的端点
      url = '/marketing/campaign/saveAndExecute';
      method = 'put';
      action = '保存并执行';
    }
  } else {
    // 新增操作
    if (form.status === 'draft') {
      url = '/marketing/campaign/save';
      method = 'post';
      action = '保存草稿';
    } else {
      url = '/marketing/campaign/saveAndExecute';
      method = 'post';
      action = '保存并执行';
    }
  }

  // 格日期字段为 yyyy-MM-dd HH:mm:ss 格式
  const formatDate = (date) => {
    if (!date) return null
    if (typeof date === 'string') return date
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hours = String(d.getHours()).padStart(2, '0')
    const minutes = String(d.getMinutes()).padStart(2, '0')
    const seconds = String(d.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  // 准备请求数据
  const requestData = {
    ...form,
    // 格式化日期字段
    startTime: formatDate(form.startTime),
    endTime: formatDate(form.endTime),
    scheduledTime: formatDate(form.scheduledTime),
    // 确保客户群体和营销方式是字符串格式
    customerGroup: typeof form.customerGroup === 'string' ? form.customerGroup : JSON.stringify(form.customerGroup),
    marketingMethods: typeof form.marketingMethods === 'string' ? form.marketingMethods : JSON.stringify(form.marketingMethods)
  };

  // 发送请求
  request({
    url: url,
    method: method,
    data: requestData
  }).then(response => {
    if (response.code === "0") {
      modal.msgSuccess(`${action}成功`);
      open.value = false;
      getList();
    } else {
      modal.msgError(response.message || `${action}失败`);
    }
  }).catch(error => {
    console.error("请求错误:", error);
    modal.msgError(`${action}失败: ${error.message || '未知错误'}`);
  });
}

// 初始化数据
getList();
</script>

<style scoped>
.common-card {
  margin-bottom: 15px;
}
.btn-form {
  margin-bottom: 15px;
}
.btn-form .el-button {
  margin-right: 10px;
}
</style>